package com.pkk.penguin.frame.know.java.practice.stack.impl.array;

import java.util.EmptyStackException;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: 用数组实现栈
 * @author: peikunkun
 * @create: 2020-01-03 15:59
 **/
@Slf4j
public class StackArray {

  /**
   * 栈的数组实现
   */
  private Object[] array;
  /**
   * 栈顶-指针
   */
  private volatile int pointer_top;

  /**
   * 默认栈最大值
   */
  private final static int SIZE = 100;

  public StackArray() {
    array = new Object[SIZE];
    //栈空的时候为-1
    pointer_top = -1;
  }


  /**
   * @Description: 压栈
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/1/3 0003 下午 4:09
   */
  public synchronized void push(Object o) {
    if (pointer_top == array.length - 1) {
      throw new StackOverflowError("数组版的栈溢出错误!");
    } else {
      array[++pointer_top] = o;
    }
  }

  /**
   * @Description: 弹栈
   * @return: java.lang.Object
   * @Author: peikunkun
   * @Date: 2020/1/3 0003 下午 4:17
   */
  public synchronized Object pop() {
    if (pointer_top == -1) {
      throw new EmptyStackException();
    }
    return array[pointer_top--];
  }


  /**
   * @Description: 判断是否为空
   * @return: boolean
   * @Author: peikunkun
   * @Date: 2020/1/3 0003 下午 4:17
   */
  public synchronized boolean isEmpty() {
    return pointer_top == -1;
  }

  /**
   * @Description: 返回栈顶元素
   * @return: java.lang.Object
   * @Author: peikunkun
   * @Date: 2020/1/3 0003 下午 4:18
   */
  public synchronized Object peek() {
    if (pointer_top == -1) {
      throw new EmptyStackException();
    }
    return array[pointer_top];
  }


}
